import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Tooltip from '@kuiper-components/tooltip';
import Input from '@kuiper-components/input';

import WarningsStatusEdit from '../../../../components/WarningsStatusEdit';
import Empty from '../../../../components/empty/EmptyData';
import CopyBoard from '../../../../components/CopyBoard';
import { datetime, number } from '../../../../../common/formatter';
import Table from '@knownsec/react-component/dist/Table';
import Select from '@knownsec/react-component/dist/Select';
import Button from '@knownsec/react-component/dist/Button';
import Icon from './icon';
import { Link } from 'react-router-dom';
import EventDetail from './EventDetail';
import s from './style.module.css';
import { WARNING_CATEGORY_KEY_LABEL_MAP, CONTENT_KEYWORD_TYPES } from '../../../../../common/constants';
import IgnoreRiskConfirm from '../../../../components/IgnoreRiskDialog';

const levelMap = {
	5: '严重',
	4: '高危',
	3: '中危',
	2: '低危'
}
function warningStatsBuilder(warning = {}) {
	let text;
	if (warning.ignoredTime) {
		text = (
			<Tooltip
				placement="top"
				overlay={
					<span className={s.time}>
						忽略操作: {datetime(warning.ignoredTime)}
					</span>
				}
			>
				<span className={s.ignored}>已忽略</span>
			</Tooltip>
		);
	} else if (warning.isResolved) {
		text = <span className={s.resolved}>已处理</span>;
	} else {
		text = <span className={s.notResolved}>待处理</span>;
	}
	return text;
}
const levelColor = {
	5: '#D5342F',
	4: '#F04038',
	3: '#F18246',
	2: '#FCD94A'
}
function NewTable({
	className,
	category,
	tableData,
	isModified,
	cydEnabled,
	taskId,
	linkType,
	refetch,
	loading,
	tp,
	notStatus,
	empty,
	jid,
	id,
	atid,
	isHistory,
	taskType,
	refresh
}) {
	const titleObj = {
		keyword: '敏感词数',
		privacy_disclosure: '隐私信息数',
	};
	const [filter, setFilter] = React.useState({ type: '' })
	const filterTableData = React.useMemo(() => {
		return tableData.reduce((total, item) => {

      const originDetailCount = {
        phone_number: { label: '手机号', value: 0 },
        bank_card_number: { label: '银行卡号', value: 0 },
        email: { label: '邮箱号', value: 0 },
        id_number: { label: '身份证号', value: 0 }
      }

      const keywordDetailCount = CONTENT_KEYWORD_TYPES.reduce((t, item) => {
        t[item.idx] = { label: item.label, value: 0 }
        return t
      }, {})

      const detailCount = category === 'keyword' ? keywordDetailCount : originDetailCount
      const additionResult = item?.addition?.results || []


      Object.values(additionResult)?.map(i => {
        Object.keys(detailCount).map(key => {
          if (category === 'keyword') {
            detailCount[key].value += +i.type === +key ? 1 : 0
          } else {
            detailCount[key].value += i.type_name === key ? 1 : 0
          }
        })
      })

			item = {...item, ...Object.keys(detailCount).reduce((t, k) => { t[k] = detailCount[k].value; return t }, {}) }

      if (filter?.type) {
				item[filter?.type] && total.push(item)
			} else {
				total.push(item)
			}
			return total
		}, [])
	}, [tableData, filter])
	const [colum, setColum] = React.useState([]);
	const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRowKeys(newSelectedRowKeys);
	};
	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	};
	const nodeRef = React.useRef();

	const columns = [
		{
			title: '风险地址',
			dataIndex: 'affects',
			key: 'affects',
			width: 550,
			// eslint-disable-next-line react/display-name
			render: affects => {
				return <CopyBoard className={s.affect} text={affects} />;
			},
		},
		{
			title: '威胁等级',
			dataIndex: 'level',
			key: 'level',
			render () {
				const e = 2 // 内容违规威胁类型都为低危
				return <span style={{color: levelColor[e]}}>{levelMap[e]}</span>
			}
		},
		{
			title: '操作',
			key: 'oper',
			render(cur, record) {
				const url = linkType
					? `/asset-manage/manage/web/content-detail/${record.tid}/DetailC`
					: `/job-manage/web-task/content-detail/${record.tid}/DetailC`;
				return (
					<>
						<Link
							to={{
								pathname: url,
								sendState: {
									jid, atid,
									taskId: record.tid,
									taskType,
									id: record._id,
									title: record.title,
									cydEnabled,
									isHistory,
									url: record?.affects,
								},
							}}
						>
							查看详情
						</Link>
						<IgnoreRiskConfirm className={'ml5'} data={{ task_id: record.tid, warning_ids: [record._id] }} refresh={refresh} />
					</>
				);
			},
		},
	];
	React.useEffect(() => {
		const mingan = {
			title: '敏感词数',
			key: 'hack',
			render(cur, d) {
				return (
					<div>
						{number(
							Object.values(d.detail).reduce((s, words) => {
								words.map(x => s.add(x));
								return s;
							}, new Set()).size
						)}
					</div>
				);
			},
		};
		const secret = {
			title: '隐私信息数',
			key: 'bad',
			render(cur, d) {
				const detailCount = {
					phone_number: {label: '手机号', value: 0},
					bank_card_number: {label: '银行卡号', value: 0},
					email: {label: '邮箱号', value: 0},
					id_number: {label: '身份证号', value: 0}
				}
				Object.values(d?.addition?.results).map(item => {
					Object.keys(detailCount).map(key => {
						detailCount[key].value += item.type_name === key ? 1 : 0
					})
				})
				return (
					<Tooltip
						placement="top"
						overlay={<div className={s.typeTooltip}>
							{Object.keys(detailCount).map(key => {
								return <div>
									<p>{detailCount[key].label}</p>
									<p>{detailCount[key].value}</p>
								</div>
							})}
						</div>}
						overlayClassName={s.dropdown}>
							<div className={s.secuType}>{Object.keys(detailCount).map(key => {
								return <div>{detailCount[key].value}</div>
							})}</div>
					</Tooltip>
					// <div>
					// 	{number(
					// 		Object.values(d.detail).reduce((s, words) => {
					// 			words.map(x => s.add(x));
					// 			return s;
					// 		}, new Set()).size
					// 	)}
					// </div>
				);
			},
		};
		if (titleObj.hasOwnProperty(category)) {
			const co = [...columns];
			co.splice(
				1,
				0,
				mingan.title.includes(titleObj[category]) ? mingan : secret
			);
			setColum(co);
		} else {
			setColum(columns);
		}
	}, [category]);

	const handleResetSelected = () => {
		setSelectedRowKeys([]);
	};
	const style = { display: 'flex', 'align-items': 'center' };

	return (
		<div className={cn(className, s.tableWapper)} ref={nodeRef}>
			<div className={s.title}>
				{WARNING_CATEGORY_KEY_LABEL_MAP.content[category]}
				<span className={s.num}>({filterTableData.length})</span>
				{/* <Tooltip placement="top" overlay={<span>低危</span>}>
					<span style={style}>
						<Icon />
					</span>
				</Tooltip> */}
				<Select className={s.mlAuto} placeholder={category === 'keyword' ? '请选择敏感词类型' : '请选择隐私信息类型'}
					value={[filter.type]}
					clearable
					onChange={({ selectedItem }) => setFilter({type: selectedItem[0]?.value || ''})}
					option={category === 'keyword' ? CONTENT_KEYWORD_TYPES.reduce((t, item) => {
						t.push({ label: item.label, value: item.idx })
						return t
					}, []) : [
					{ label: '手机号', value: 'phone_number' },
					{ label: '银行卡号', value: 'bank_card_number' },
					{ label: '邮箱号', value: 'email' },
					{ label: '身份证号', value: 'id_number' }
				]} />
				<Button className='primary-btn ml10' onClick={() => setFilter({type: ''})}>重置</Button>
			</div>
			{isModified ? (
				<>
					<Table
						loading={loading}
						columns={colum}
						data={filterTableData}
						pro
						rowSelection={notStatus ? {} : rowSelection}
						empty={empty}
						scroll={filterTableData.length ? { y: '235px', x: true } : {}}
					/>
					<div>
						<IgnoreRiskConfirm className={'p0 mt5'}
							text='批量忽略'
							disabled={selectedRowKeys?.length === 0}
							data={{ warning_ids: selectedRowKeys, task_id: filterTableData[0]?.tid }} refresh={r_ => {
								refresh(r_)
								handleResetSelected()
							}} />
					</div>
				</>
			) : (
				<Table
					loading={loading}
					columns={colum}
					data={filterTableData}
					pro
					empty={empty}
					scroll={filterTableData.length ? { y: '235px', x: true } : {}}
				/>
			)}
		</div>
	);
}

NewTable.propTypes = {
	className: PropTypes.string,
	category: PropTypes.string.isRequired,
	tableData: PropTypes.array,
	isModified: PropTypes.bool,
	taskId: PropTypes.string,
	refetch: PropTypes.func,
	cydEnabled: PropTypes.bool,
};
NewTable.defaultProps = {
	className: '',
	isModified: true,
	tableData: [],
};

export default NewTable;
